package com.xuhai.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.Polygon;
import com.vividsolutions.jts.io.WKTReader;
import org.geotools.geometry.jts.JTSFactoryFinder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 判断输入点坐标是否在图形内
 * @author admin
 *
 */
public class IsPointInPolygon {

	static GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();

	static double a = 6378245.0;
	static double ee = 0.00669342162296594323;
	static double PI = 3.1415926535897932384626;

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		// 点集范围
		double[][] p = { { 11934072.91, 3213322.45 }, { 11958532.76, 3188862.6 }, { 11929180.94, 3186416.62 },
				{ 11934072.91, 3213322.45 } };

		double lng = 107.2646132;
		double lat = 27.602171;
		Boolean b = isInPolygon(p, lng, lat);

		System.out.print(b);
	}

	public static Boolean isInPolygon(double[][] p, double lng, double lat) {
		String ptsStr = "(";
		for (double[] xy : p) {
			ptsStr += xy[0] + " " + xy[1] + ",";
		}
		ptsStr = ptsStr.substring(0, ptsStr.length() - 1);

		ptsStr += ")";

		Polygon polygon = createPolygonByPts(ptsStr);

		// 坐标转换
		double[] marXY = transform(lng, lat);
		double[] webXY = latLng2WebMercator(marXY[0], marXY[1]);

		Point pt = createPointByXY(webXY[0], webXY[1]);
		pt.setSRID(3857);

		return polygon.contains(pt);

	}

	/**
	 * 将两个坐标构建为Point
	 * @param x和y
	 * @return LineString
	 */
	public static Point createPointByXY(double x, double y) {
		String pointString = "POINT(" + x + " " + y + ")";

		WKTReader reader = new WKTReader(geometryFactory);
		Point pt = null;
		try {
			pt = (Point) reader.read(pointString);

		} catch (com.vividsolutions.jts.io.ParseException e) {
			e.printStackTrace();
		}
		return pt;
	}

	/**
	 * 将组成面的坐标字符串构建为polygon
	 * @param 
	 * @return polygon
	 */
	public static Polygon createPolygonByPts(String pts) {
		String pointString = "POLYGON(" + pts + ")";

		WKTReader reader = new WKTReader(geometryFactory);
		Polygon pg = null;
		try {
			pg = (Polygon) reader.read(pointString);

		} catch (com.vividsolutions.jts.io.ParseException e) {
			e.printStackTrace();
		}
		return pg;
	}

	/**
	 * WGS1984经纬度转web Mercator
	 * 
	 * @param double lng 经度
	 * @param double lat 纬度
	 * 
	 * @return double[] 
	 * */
	public static double[] latLng2WebMercator(double lng, double lat) {
		double earthRad = 6378137.0;
		double[] xy = new double[2];
		double x = lng * Math.PI / 180 * earthRad;
		double a = lat * Math.PI / 180;
		double y = earthRad / 2 * Math.log((1.0 + Math.sin(a)) / (1.0 - Math.sin(a)));
		xy[0] = x;
		xy[1] = y;
		return xy;
	}

	public static double[] transform(double wgLon, double wgLat) {
		double mgLat = 0;
		double mgLon = 0;
		if (outOfChina(wgLat, wgLon)) {
			mgLat = wgLat;
			mgLon = wgLon;
			return null;
		}

		double dLat = transformLat(wgLon - 105.0, wgLat - 35.0);
		double dLon = transformLon(wgLon - 105.0, wgLat - 35.0);
		double radLat = wgLat / 180.0 * PI;
		double magic = Math.sin(radLat);
		magic = 1 - ee * magic * magic;
		double sqrtMagic = Math.sqrt(magic);
		dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * PI);
		dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * PI);
		mgLat = wgLat + dLat;
		mgLon = wgLon + dLon;

		double[] a = { mgLon, mgLat };

		return a;
	}

	public static boolean outOfChina(double lat, double lon) {
		if (lon < 72.004 || lon > 137.8347)
			return true;
		if (lat < 0.8293 || lat > 55.8271)
			return true;
		return false;
	}

	public static double transformLat(double x, double y) {
		double ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
		ret += (20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0 / 3.0;
		ret += (20.0 * Math.sin(y * PI) + 40.0 * Math.sin(y / 3.0 * PI)) * 2.0 / 3.0;
		ret += (160.0 * Math.sin(y / 12.0 * PI) + 320 * Math.sin(y * PI / 30.0)) * 2.0 / 3.0;
		return ret;
	}

	public static double transformLon(double x, double y) {
		double ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
		ret += (20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0 / 3.0;
		ret += (20.0 * Math.sin(x * PI) + 40.0 * Math.sin(x / 3.0 * PI)) * 2.0 / 3.0;
		ret += (150.0 * Math.sin(x / 12.0 * PI) + 300.0 * Math.sin(x / 30.0 * PI)) * 2.0 / 3.0;

		return ret;
	}

	public static double[][] transferToDouble2Array(String str){
		String[][] arr = JSON.parseObject(str, String[][].class);
		double[][] ds = new double[arr.length][arr[0].length];
		for(int j=0;j<arr.length;j++){
			for(int i=0;i<arr[0].length;i++){
				ds[j][i] = Double.valueOf(arr[j][i]);
			}
		}
		return ds;
	}

	public static double[][] getPloyon(String resultStr, int i){
		JSONArray rings = JSON.parseObject(resultStr).getJSONArray("features").getJSONObject(i).getJSONObject("geometry").getJSONArray("rings").getJSONArray(0);
		return IsPointInPolygon.transferToDouble2Array(rings.toJSONString());
	}

	public static Map<String,List<String>> getCityPloyonMap(String resultStr){
		Map<String, List<String>> resultMap = new HashMap<String,List<String>>();
		JSONArray features = JSON.parseObject(resultStr).getJSONArray("features");
		if(features == null || features.size() == 0) return null;
		int length = features.size();
		for (int i =0; i< length; i++) {
			JSONObject object = features.getJSONObject(i);
			String city = object.getJSONObject("attributes").getString("cityCode");
			if(resultMap.get(city) == null){
				List<String> ployonList = new ArrayList<String>();
				ployonList.add(object.getJSONObject("geometry").getJSONArray("rings").getJSONArray(0).toJSONString());
				resultMap.put(city, ployonList);
			}else{
				List<String> ployonList = resultMap.get(city);
				ployonList.add(object.getJSONObject("geometry").getJSONArray("rings").getJSONArray(0).toJSONString());
				resultMap.put(city, ployonList);
			}
		}
		return resultMap;
	}

}
